var assert = require('../assert');
var jade = require('jade');
exports.render = function (req, res, next) {
    var shopId = 'ZBiUkk2Azw';
    var JADE_VAR = assert.getJADEVAR();
    assert.apiParseRequest('get','/kdShop/'+shopId,{}).then(function(results){

        var shopInfo = results.shopInfo;
        var shopProducts = results.shopProducts;
        var news  = shopProducts.news;
        delete shopProducts.news;
        JADE_VAR.shopInfo = shopInfo;
        JADE_VAR.news = news;
        JADE_VAR.Products = shopProducts;
        JADE_VAR.navStyle = shopInfo.naviStyle;
        console.log(news);
        console.log(shopProducts);
        var nav = [];
        for(var key in shopProducts){
            nav.push(key);
        }
        JADE_VAR.nav = nav;
        console.log(JADE_VAR);
        /*var waitRender = [
          renderPromise(res, 'template/'+shopInfo.template, JADE_VAR),
          renderPromise(res, 'template/'+shopInfo.naviStyle, JADE_VAR),
          renderPromise(res, 'template/'+shopInfo.listStyle, JADE_VAR)
        ];*/
        var waitRender = [
            renderPromise(res, 'template/'+shopInfo.template, JADE_VAR),
            renderPromise(res, 'template/'+'navSort',  JADE_VAR),
            renderPromise(res, 'template/'+'proList', JADE_VAR)
        ];

      Promise.all(waitRender).then(function (results) {

          res.render('shop/shop', {header: results[0],navigation:results[1], product: results[2]})
      }, function (err) {
          console.log(err);
      });

  },function (err,error) {
        res.render('error',assert.getRes(404,err,{},true));
    });

};

function renderPromise(res, jadePath, data) {
    return new Promise(
        function (resolve, reject) {
            res.render(jadePath, data, function (err, htmlStr) {
                if (!err) {
                    resolve(htmlStr);
                } else {
                    console.log(err);
                    reject("编译" + jadePath + "文件失败");
                }
            })
        }
    )
}